package com.stuManager.servlet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.stuManager.dao.UserDao;
import com.stuManager.model.CommonResponseModel;
import com.stuManager.model.User;
import com.stuManager.service.LoginService;
import com.stuManager.util.CookiesUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
/*
    TokenLoginServlet
    通过登录接口生成的token自动登录的接口
    目前是在login.html调用，如果发现token仍有效就会直接跳转到学生管理系统主页，不用再登录
 */
@WebServlet(name = "TokenLoginServlet", value = "/tokenLogin")
public class TokenLoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.创建service
        LoginService service = new LoginService();
        //2. 获取请求中cookie里的token
        Cookie token = CookiesUtil.getCookieByName(request, "token");
        //3. 通过service尝试登录，获取处理结果
        CommonResponseModel m = service.tokenLoginService(token.getValue());
        //4. 准备要返回的数据
        response.setContentType("application/json");
        String jsonString = JSON.toJSONString(m);
        response.getWriter().print(jsonString);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
